package cn.edu.zjicm.wordsnet_d.fragment;

import java.util.Arrays;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.ExamSpellActivity;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.media.VoicePlayer;
import cn.edu.zjicm.wordsnet_d.util.TypefaceUtil;

public class ExamSpellFragment extends Fragment implements OnClickListener{	
	
	public ExamSpellFragment(OneWord word, ExamSpellActivity examRunActivity) {
		this.mOneWord = word;
		this.mExamRunActivity = examRunActivity;
	}
	
	public ExamSpellFragment(){
		
	}
	
	private ExamSpellActivity mExamRunActivity;
	// Data
	private OneWord mOneWord;
	// View
	private TextView mWordPhonetic;
	private TextView mWordCn;
	// 右上角按钮
	private LinearLayout mReadButton;
	//
	private int mCurrentBlankIndex;
	private int[] mBlankIndexArray;
	private String mEn;
	private char []letters;
	//View 
	private LinearLayout mWordContainer;
	private TextView mWordContainerIndependent;
	private LinearLayout mLetterContainer,mLetterContainer2,mLetterContainer3,mLetterContainer4;
	private TextView[] mBlanks;
	private ImageView mRightOrWrongIcn;
	private boolean isRight = false;
	private int wordLength;
	private TextView letterTexts[],clickedLetterText[];
	private int lengthOfListener;
	private TextView blankTextView;
	
	private Button promptButton, rewriteButton, nextButton;
	private TextView backspaceButton;
	private String stringInput;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_exam_spell, null);
		
		mWordPhonetic = (TextView) v.findViewById(R.id.word_detail_phonetic);
		TypefaceUtil.getInstance(mExamRunActivity).setTypeface(mWordPhonetic);
		mWordCn = (TextView) v.findViewById(R.id.word_detail_cn);
		mReadButton = (LinearLayout) v.findViewById(R.id.read_button);

		promptButton = (Button) v.findViewById(R.id.test_prompt_button);//提示按钮
		rewriteButton = (Button) v.findViewById(R.id.test_rewrite_button);
		nextButton = (Button) v.findViewById(R.id.test_next_button);
		backspaceButton = (TextView) v.findViewById(R.id.backspaceButton);
		
		mWordContainer = (LinearLayout) v.findViewById(R.id.write_word_container);
		mWordContainerIndependent = (TextView) v.findViewById(R.id.write_word_container_independent);
		mLetterContainer = (LinearLayout) v.findViewById(R.id.write_letter_container);
		mLetterContainer2 = (LinearLayout) v.findViewById(R.id.write_letter_container2);
		mLetterContainer3 = (LinearLayout) v.findViewById(R.id.write_letter_container3);
		mLetterContainer4 = (LinearLayout) v.findViewById(R.id.write_letter_container4);
		mRightOrWrongIcn = (ImageView) v.findViewById(R.id.write_right_or_wrong_icn);	
		
		if(mOneWord != null)
			initView();
		return v;
	}	
	
	public void initViewForNewWord(OneWord word){
		this.mOneWord = word;
		initView();
	}
	
	private void initView() {
		mEn = mOneWord.getLemma();

		initWriteView(mEn);
		reWriteIndependent();		
		
		mWordPhonetic.setText(mOneWord.getPhonetic());
		mWordCn.setText(mOneWord.getSensesSenior());
			
		if(AppPreference.isAutoPronunciation(mExamRunActivity)){
			VoicePlayer.getInstance(getActivity()).play(mOneWord);
		}
		
		mReadButton.setOnClickListener(this);	
		promptButton.setOnClickListener(this);
		rewriteButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);
		backspaceButton.setOnClickListener(this);	
	}
	
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if(view == mReadButton){			// 播放读音
			VoicePlayer.getInstance(getActivity()).play(mOneWord);
		} else if(view == rewriteButton) {
			reWriteIndependent();	
			ifBackspaceButtonOn(mCurrentBlankIndex);
		} else if(view == nextButton) {
			mExamRunActivity.next();			
		} else if(view == promptButton) {
			VoicePlayer.getInstance(getActivity()).play(mOneWord);
			Toast.makeText(getActivity(), mOneWord.getLemma(), Toast.LENGTH_SHORT).show();
		} else if(view == backspaceButton) {
			if(mCurrentBlankIndex>0){
				mCurrentBlankIndex--;
				clickedLetterText[mCurrentBlankIndex].setBackgroundResource(R.drawable.write_letter);
				clickedLetterText[mCurrentBlankIndex].setTextColor(Color.rgb(114,109,101));
				clickedLetterText[mCurrentBlankIndex].setClickable(true);
//				mBlanks[/*mBlankIndexArray[*/mCurrentBlankIndex/*]*/].setText(" ");
				stringInput = stringInput.substring(0,stringInput.length()-1);
				mWordContainerIndependent.setText(stringInput);
			}
			ifBackspaceButtonOn(mCurrentBlankIndex);
		}
	}
	
	/**
	 * 再写一遍，重写
	 * 重新构建抄写
	 */	
	public void reWriteIndependent(){
		VoicePlayer.getInstance(getActivity()).play(mOneWord);		
		initWriteViewIndependent(mEn);

		promptButton.setEnabled(true);
		isRight = false;
	}
	
	private void initWriteViewIndependent(final String word){
		mWordContainerIndependent.setVisibility(View.VISIBLE);
		mWordContainer.setVisibility(View.GONE);
		wordLength = word.length();
		
//		final LayoutParams lp = mWordContainerIndependent.getLayoutParams();
//		lp.width = 30*wordLength;
//		mWordContainerIndependent.setLayoutParams(lp);
		
		if(TextUtils.isEmpty(word))return;
		if(word.length()<6) 
			lengthOfListener = 6;
		else lengthOfListener = word.length();
		letters = new char[lengthOfListener];
		lengthOfListener = letters.length;
		stringInput = "";
		mWordContainerIndependent.setText(stringInput);
		mLetterContainer.removeAllViews();
		mLetterContainer2.setVisibility(View.VISIBLE);
		mLetterContainer3.setVisibility(View.GONE);
		mLetterContainer4.setVisibility(View.GONE);
		mLetterContainer2.removeAllViews();
		mLetterContainer3.removeAllViews();
		mLetterContainer4.removeAllViews();
		mRightOrWrongIcn.setVisibility(View.GONE);
		mCurrentBlankIndex = 0;

		mBlanks = new TextView[word.length()];
		
		float density = getResources().getDisplayMetrics().density;
		
		for(int i=0;i<word.length();i++){
			char c = word.charAt(i);
			letters[i] = c;
			
//			mBlanks[i] = new TextView(getActivity());
//			mBlanks[i] .setTextSize(24);
//			mBlanks[i] .setGravity(Gravity.CENTER);
//			mBlanks[i] .setTextColor(getResources().getColor(R.color.write_normal_color));
//			mBlanks[i].setBackgroundResource(R.drawable.write_underline_bg);
//				//宽带由25 * density改为10 * density
//			int width = (int) (10 * density);
//			mBlanks[i] .setMinWidth(width);
//			mWordContainerIndependent.addView(mBlanks[i]);
		}
		if(word.length()<6){
			for(int i=word.length();i<6;i++){
				letters[i] = (char)((int)(Math.random()*26)+'a');
			}
		}
		Arrays.sort(letters);
		
		mWordContainerIndependent.setMinWidth(1);
		
//		Log.i("letters",letters.toString());
//		Log.i("letters.length",letters.length + "");
		
		
		letterTexts = new TextView[letters.length];
		clickedLetterText = new TextView[wordLength];
		
		for(int i = 0; i < letters.length; i++){		
				final TextView letterText = new TextView(getActivity());
				letterText.setBackgroundResource(R.drawable.write_letter);
				letterText.setGravity(Gravity.CENTER);
				letterText.setTextSize(20);
				letterText.setTextColor(Color.rgb(114,109,101));
				letterText.setText(String.valueOf(letters[i]));
				LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				para.rightMargin = (int) (14.6 * density);
//				letterText.setPadding((int) (13 * density), (int) (5 * density), (int) (13 * density), (int) (5 * density));
				if(mLetterContainer.getChildCount()<5)
					mLetterContainer.addView(letterText, mLetterContainer.getChildCount(), para);
				else if(mLetterContainer2.getChildCount()<5)
					mLetterContainer2.addView(letterText, mLetterContainer2.getChildCount(), para);
				else if(mLetterContainer3.getChildCount()<5){
					mLetterContainer3.setVisibility(View.VISIBLE);
					mLetterContainer3.addView(letterText, mLetterContainer3.getChildCount(), para);
				}else{
					mLetterContainer4.setVisibility(View.VISIBLE);
					mLetterContainer4.addView(letterText, mLetterContainer4.getChildCount(), para);
				}
				letterText.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						clickedLetterText[mCurrentBlankIndex] = letterText;//记录点击过的TextView;
						letterText.setBackgroundResource(R.drawable.write_letter_selected);
						letterText.setTextColor(Color.WHITE);
						letterText.setClickable(false);
//						mBlanks[/*mBlankIndexArray[*/mCurrentBlankIndex/*]*/].setTextColor(getResources().getColor(R.color.write_right_color));
//						mBlanks[/*mBlankIndexArray[*/mCurrentBlankIndex/*]*/].setText(letterText.getText());
						stringInput += letterText.getText();
						mWordContainerIndependent.setText(stringInput);
						mCurrentBlankIndex++;
						ifBackspaceButtonOn(mCurrentBlankIndex);
						if(mCurrentBlankIndex == wordLength){
							writeEndIndependent();
						}
					}
				});
				letterTexts[i] = letterText;
		}
	}
	
	private void ifBackspaceButtonOn(int n){
		try {
			if(n>0){
				backspaceButton.setClickable(true);
				backspaceButton.setVisibility(View.VISIBLE);
//				backspaceButton.setBackgroundResource(R.drawable.backspace);
			}else{
				backspaceButton.setVisibility(View.GONE);
//				backspaceButton.setBackgroundResource(R.drawable.backspace_selected);
			}
		} catch (Exception e) {
			Log.i("e",e+"");
			Log.i("n",n+"");			
		}		
	}

	private void initWriteView(String word){
		mWordContainerIndependent.setVisibility(View.GONE);
		mWordContainer.setVisibility(View.VISIBLE);
		if(TextUtils.isEmpty(word))return;
		mWordContainer.removeAllViews();
		mLetterContainer.removeAllViews();
		mLetterContainer2.setVisibility(View.GONE);
		mLetterContainer3.setVisibility(View.GONE);
		mLetterContainer4.setVisibility(View.GONE);
		mRightOrWrongIcn.setVisibility(View.GONE);
		mCurrentBlankIndex = 0;
		mBlanks = new TextView[word.length()];
		
		float density = getResources().getDisplayMetrics().density;
		mBlankIndexArray = generateRandomBlanks(word.length());
		letterTexts = new TextView[mBlankIndexArray.length+1];
		int listenIndex=0;//监听数组的index
		for(int i = 0; i < word.length(); i++){
			char c = word.charAt(i);
			mBlanks[i] = new TextView(getActivity());
			mBlanks[i] .setTextSize(24);
			mBlanks[i] .setGravity(Gravity.CENTER);
			mBlanks[i] .setTextColor(getResources().getColor(R.color.write_normal_color));
			if(isBlank(i, mBlankIndexArray)){
				mBlanks[i].setBackgroundResource(R.drawable.write_underline_bg);
				//宽带由25 * density改为10 * density
				int width = (int) (10 * density);
				mBlanks[i] .setMinWidth(width);
				final TextView letterText = new TextView(getActivity());
				letterText.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						letterText.setBackgroundResource(R.drawable.write_letter_selected);
						letterText.setTextColor(Color.WHITE);
						letterText.setClickable(false);
						mBlanks[mBlankIndexArray[mCurrentBlankIndex]].setTextColor(getResources().getColor(R.color.write_right_color));
						mBlanks[mBlankIndexArray[mCurrentBlankIndex]].setText(letterText.getText());
						mCurrentBlankIndex++;
						
						if(mCurrentBlankIndex == mBlankIndexArray.length)writeEnd();
					}
				});
				letterText.setBackgroundResource(R.drawable.write_letter);
				letterText.setTextColor(Color.rgb(114,109,101));
				letterText.setGravity(Gravity.CENTER);
				letterText.setTextSize(20);
				letterText.setTextColor(Color.WHITE);
				letterText.setText(String.valueOf(c));
				LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				para.rightMargin = (int) (20 * density);
				int index = (int) (Math.random() * (mLetterContainer.getChildCount() + 1));
				mLetterContainer.addView(letterText, index, para);
				letterTexts[listenIndex] = letterText;//添加监听数组
				listenIndex++;
			}else{
				mBlanks[i] .setText(String.valueOf(c));
			}
			mWordContainer.addView(mBlanks[i]);
		}
		final TextView letterText = new TextView(getActivity());
		letterText.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				letterText.setBackgroundResource(R.drawable.write_letter_selected);
				letterText.setTextColor(Color.WHITE);
				letterText.setClickable(false);
				if(mCurrentBlankIndex == mBlankIndexArray.length) return;
				mBlanks[mBlankIndexArray[mCurrentBlankIndex]].setTextColor(getResources().getColor(R.color.write_right_color));
				mBlanks[mBlankIndexArray[mCurrentBlankIndex]].setText(letterText.getText());
				mCurrentBlankIndex++;
				if(mCurrentBlankIndex == mBlankIndexArray.length)
					writeEnd();
			}
		});
		letterText.setBackgroundResource(R.drawable.write_letter);
		letterText.setTextColor(Color.rgb(114,109,101));
		letterText.setGravity(Gravity.CENTER);
		letterText.setTextSize(20);
		letterText.setTextColor(Color.WHITE);
		letterText.setText(String.valueOf((char)((int)(Math.random()*26)+'a')));
		LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		para.rightMargin = (int) (20 * density);
		int index = (int) (Math.random() * (mLetterContainer.getChildCount() + 1));
		mLetterContainer.addView(letterText, index, para);
		letterTexts[listenIndex] = letterText;//添加监听数组
		lengthOfListener = letterTexts.length;
	}
	
	/**
	 * 拼写完毕时执行
	 */
	private void writeEnd(){
		isRight = true;
		for(int i = 0; i < mBlankIndexArray.length; i++){
			int index = mBlankIndexArray[i];
			TextView blankTv = mBlanks[index];
			if(!blankTv.getText().equals(String.valueOf(mEn.charAt(index)))){
				blankTv.setTextColor(getResources().getColor(R.color.write_wrong_color));
				isRight = false;
			}
		}
		showWriteResult(isRight);
	}
	
	private void writeEndIndependent(){
		isRight = true;
		promptButton.setEnabled(false);
		backspaceButton.setVisibility(View.GONE);
//		backspaceButton.setClickable(false);
//		backspaceButton.setBackgroundResource(R.drawable.backspace_selected);

		for(int i = 0; i < wordLength; i++){
			char blankTv = stringInput.charAt(i);
			if(blankTv!=mEn.charAt(i)){
//				blankTv.setTextColor(getResources().getColor(R.color.write_wrong_color));
				isRight = false;
			}
		}
		showWriteResult(isRight);
	}	
	
	public void showWriteResult(boolean isRight){
		for(int j=0;j<lengthOfListener;j++){
			letterTexts[j].setBackgroundResource(R.drawable.write_letter_selected);
			letterTexts[j].setTextColor(Color.WHITE);
			letterTexts[j].setClickable(false);
		}
		
		mRightOrWrongIcn.setVisibility(View.VISIBLE);
		if(isRight){
			mRightOrWrongIcn.setImageResource(R.drawable.right_ico);
			// 拼写正确播放读音
			VoicePlayer.getInstance(getActivity()).play(mOneWord);
		}else{
			mRightOrWrongIcn.setImageResource(R.drawable.wrong_ico);
		}
		setIsRight(isRight);
	}
	
	public boolean getIsRight(){
		return isRight;
	}
	
	public void setIsRight(boolean isRight){
		this.isRight = isRight;
	}
	
	private boolean isBlank(int index, int[] blanks){
		for(int i : blanks){
			if(index == i)return true;
		}
		return false;
	}
	
	private int[] generateRandomBlanks(int count){
		int[] randomBlanks = null;
		switch(count){
		case 0:
			break;
		case 1:
			break;
		case 2:
			//只有1~2个字母的单词时，空格为第一字母
			//randomBlanks = new int[1];
			//randomBlanks[0] = 0;
			//break;
		case 3:
		case 4:
		case 5:
		case 6:
			//有3~6个字幕的单词时，空格为中间
			randomBlanks = new int[2];
			for(int i = 0; i < randomBlanks.length; i++){
				randomBlanks[i] = i + 1;
			}
			break;
		default:
			//其他默认情况，在除首尾外随机产生4或则5个
			int randomCount = 3;
//			if(count > 8)randomCount = 5;
			randomBlanks = new int[randomCount];
			int actualCount = count - 2;
			int[] actualArray = new int[actualCount];
			for(int i = 0; i < actualArray.length; i++){
				actualArray[i] = i + 1;
			}
			int unnecessaryCount = actualCount - randomCount;
			while(unnecessaryCount != 0){
				int random = (int) (Math.random() * actualCount);
				if(actualArray[random] != -1){
					actualArray[random] = -1;
					unnecessaryCount--;
				}
			}
			int index = 0;
			for(int i = 0; i < actualArray.length; i++){
				if(actualArray[i] != -1){
					randomBlanks[index] = actualArray[i];
					index++;
				}
			}
			break;
		}
		return randomBlanks;
	}

}